/**
 * 用户购买记录查询
 *
 * @format
 */

import * as dayjs from 'dayjs'
import { dateFormatter, transformBeijingDate, TBAPIS } from '../../sdk'
import { getSellerSession } from './getSession'
import { TAOBAO_SUCCESS_ORDER_STATUS } from '../../constants'

export const getUserOrderlist = async (context, queryStartTime, queryEndTime?, session?: string) => {
  try {
    let results = []
    let currentTime = Date.now()
    // 开始时间以Math.max(当前时间倒推3个月，queryStartTime)
    let lastUpdateTime = dayjs().add(-3, 'month').valueOf()
    console.log(`lastUpdateTime`, lastUpdateTime)
    // 若倒推的3个月时间小于传入的查询开始时间, 则以查询开始时间作为最后更新时间
    if (lastUpdateTime < queryStartTime) {
      lastUpdateTime = queryStartTime
    }
    if (!session) {
      session = (await getSellerSession(context)).session
    }
    // 获取用户在lastUpdateTime ~ currentTime区间的购买情况
    let params = {
      startTime: dateFormatter(transformBeijingDate(lastUpdateTime)),
      endTime: dateFormatter(transformBeijingDate(queryEndTime || currentTime)),
      openId: context.openId,
      session
    }
    let orderResult = await TBAPIS.getBuyerOrderList(context, params)
    if (orderResult.total_results > 0) {
      const { trade } = orderResult.trades
      trade.forEach(i => {
        if (TAOBAO_SUCCESS_ORDER_STATUS.includes(i.status)) {
          i?.orders?.order?.forEach(s => {
            results.push({
              payTime: i.pay_time,
              itemId: s.num_iid,
              time: i.created,
              price: s.price,
              orderId: s.oid,
              img: s.pic_path,
              title: s.title,
              tId: i.tid
            })
          })
        }
      })
    }
    console.log(`已支付的订单列表`, results)
    return results
  } catch (e) {
    console.log(`错误`, e)
    return []
  }
}
